package com.gym.controller.action.admin;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.gym.model.dao.ConnessioneException;
import com.gym.model.dao.DAOCourse;
import com.gym.model.dao.DAOPayment;
import com.gym.model.dao.DatoNonTrovatoException;
import com.gym.model.dao.MetodoDaoException;
import com.gym.model.dao.ViolazioneIntegritaException;
import com.gym.model.email.Email;
import com.gym.model.email.InvioEmailFallitoException;
import com.gym.model.entity.Payment;
import com.gym.model.entity.User;
import com.gym.utility.Utility;

public class CompletePayment extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {

		int idUser = Integer.valueOf(request.getParameter("iduser"));
		int idCourse = Integer.valueOf(request.getParameter("idcourse"));
		int months = Integer.valueOf(request.getParameter("months"));
		
		try {
			DAOCourse daoCourse = new DAOCourse();
			DAOPayment daoPayment = new DAOPayment();
			
			double amount = Utility.discount(daoCourse.select(idCourse).getPrice(), months);
			Payment payment = new Payment(idUser, idCourse, (short) months, amount);
			
			if (daoPayment.search(idUser, idCourse)) {
				request.setAttribute("feedbackPaymentCompleted", "Ups! Pagamento non andato a buon fine!");
			} else {
				daoPayment.insert(payment);
				request.setAttribute("feedbackPaymentCompleted", "OK! Pagamento andato a buon fine!");
			}
			
			
			// invio anche una email di notifica all'utente
			Email mail=new Email();
			User user=(User) request.getSession().getAttribute("user");
			mail.sendEmail(user.getEmail(), "notifica pagamento", "ti sei iscritto ad un nostro corso");
			
			return mapping.findForward("success");

		} catch (ConnessioneException | MetodoDaoException | DatoNonTrovatoException | ViolazioneIntegritaException e) {
			request.setAttribute("error", e.getMessage());
			return mapping.findForward("failure");
		} catch (InvioEmailFallitoException e) {
			e.printStackTrace();
			request.setAttribute("error", e.getMessage());
			return mapping.findForward("failure");
		}
	}
}